package com.example.expinterview.service.impl;

import com.example.expinterview.entity.ResultBody;
import com.example.expinterview.entity.enums.ErrorCodeEnum;
import com.example.expinterview.service.IWxService;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Objects;

/**
 * @classname: WxServiceImpl
 * @description: TODO
 * @author: kaiser
 * @date: 2021/10/20 16:22
 * @version: 1.0
 */
@Service
public class WxServiceImpl implements IWxService {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;

    @Override
    public ResultBody wxLogin(String code) {
        HttpUrl url = new HttpUrl.Builder().scheme("https").host("api.weixin.qq.com")
                .addPathSegments("sns/jscode2session").addQueryParameter("appid", appid)
                .addQueryParameter("secret", secret).addQueryParameter("js_code", code)
                .addQueryParameter("grant_type", "authorization_code").build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                String responseBody = Objects.requireNonNull(response.body()).string();
                ObjectMapper mapper = new ObjectMapper();
                return ResultBody.success(mapper.readTree(responseBody));
            } else {
                return ResultBody.fail(ErrorCodeEnum.HTTP_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResultBody.fail(ErrorCodeEnum.SYSTEM_ERROR);
        }
    }
}
